#include "StdAfx.h"
#include "LogAction.h"
#include "SerialSingleton.h"
#include "../macro.h"

LogAction::LogAction(const char* pKeyWord, int  nTimeOut)
: m_strKeyWord(pKeyWord)
, m_nTimeOut(nTimeOut)
, need_exit_(false)
{
}

LogAction::~LogAction(void)
{
}

void LogAction::OnData(const char* buff, size_t size)
{
	char* p = new char[size+1];
	memset(p, 0, size);
	memcpy(p, buff, size);
	if (size > 0)
	{
		str_ += buff;

		std::size_t found = str_.find(m_strKeyWord);
		if (found != std::string::npos)
		{
			// found the key word.
			need_exit_ = true;
		}
	}
}


bool LogAction::run(void* param)
{
	DBG_PRINTF("%s\r\n",__FUNCTION__);
	MSG_PRINTF("      [LogAction]%s timeout:%d ms\r\n", m_strKeyWord.c_str(), m_nTimeOut);

	// 1. Register to serial singleton.
	SerialSingleton::getInstance().Register(this);
	// 2. wait for key word or timeout.
	int nStart = GetTickCount();
	while (!need_exit_)
	{
		if (GetTickCount() - nStart >= m_nTimeOut)
		{
			break;
		}
		Sleep(16);
	}

	// 3. unregister.
	SerialSingleton::getInstance().Unregister(this);

	return need_exit_;
}